from decimal import Decimal
from datetime import datetime
from ..repositories import family_repositories
from ..repositories.db import get_db_connection
import re

async def get_family_members(user_id):
    """
    获取家庭成员列表
    :param user_id: 用户ID
    :return: 家庭成员列表
    """
    try:
        members = await family_repositories.get_family_members(user_id)
        return {"code": 0, "data": members}
    except Exception as e:
        print(f"获取家庭成员列表失败: {str(e)}")
        return {"code": 1, "message": "获取家庭成员列表失败"}

async def get_family_bills(user_id, bill_type=None, type=None, payment_status=None, payment_method=None, member=None, current_page=1, page_size=10):
    """
    获取家庭账单列表
    :param user_id: 用户ID
    :param bill_type: 账单类型
    :param type: 支付类型
    :param payment_status: 支付状态
    :param payment_method: 支付方式
    :param member: 成员ID
    :param current_page: 当前页码
    :param page_size: 每页数量
    :return: 账单列表
    """
    try:
        bills = await family_repositories.get_family_bills(
            user_id, 
            bill_type, 
            type, 
            payment_status, 
            payment_method, 
            member
        )
        
        # 实现分页
        start_index = (current_page - 1) * page_size
        end_index = start_index + page_size
        paginated_bills = bills[start_index:end_index]

        # 格式化数据
        formatted_bills = []
        for bill in paginated_bills:
            formatted_bill = {}
            for key, value in bill.items():
                if isinstance(value, Decimal):
                    formatted_bill[key] = float(value)
                elif isinstance(value, datetime):
                    formatted_bill[key] = value.strftime('%Y/%m/%d-%H:%M:%S')
                elif value is None:
                    formatted_bill[key] = ''
                else:
                    formatted_bill[key] = value
            formatted_bill['bill_id'] = formatted_bill['id']
            del formatted_bill['id']
            del formatted_bill['user_id']
            formatted_bill['due_date'] = formatted_bill['due_date'][:10] if formatted_bill['due_date'] else ''
            formatted_bills.append(formatted_bill)

        return {"code": 0, "total": len(bills), "data": formatted_bills}
    except Exception as e:
        print(f"获取家庭账单列表失败: {str(e)}")
        return {"code": 1, "message": "获取家庭账单列表失败"}

async def get_family_info(user_id):
    """
    获取家庭信息
    :param user_id: 用户ID
    :return: 家庭信息
    """
    try:
        # 先获取用户的家庭ID
        connection = await get_db_connection()
        async with connection.cursor() as cursor:
            await cursor.execute("SELECT family_type FROM users WHERE id = %s", [user_id])
            result = await cursor.fetchone()
            if not result or not result['family_type']:
                return {"code": 1, "message": "用户未加入家庭"}
            
            family_id = result['family_type']
            
        family = await family_repositories.get_family_info(family_id)
        if family:
            return {"code": 0, "data": family}
        return {"code": 1, "message": "获取家庭信息失败"}
    except Exception as e:
        print(f"获取家庭信息失败: {str(e)}")
        return {"code": 1, "message": "获取家庭信息失败"}

async def get_family_budgets(user_id):
    """
    获取家庭预算列表
    :param user_id: 用户ID
    :return: 预算列表
    """
    try:
        budgets = await family_repositories.get_family_budgets(user_id)
        
        # 格式化数据
        formatted_budgets = []
        for budget in budgets:
            formatted_budget = {}
            for key, value in budget.items():
                if isinstance(value, Decimal):
                    formatted_budget[key] = float(value)
                else:
                    formatted_budget[key] = value
            formatted_budgets.append(formatted_budget)
            
        return {"code": 0, "data": formatted_budgets}
    except Exception as e:
        print(f"获取家庭预算列表失败: {str(e)}")
        return {"code": 1, "message": "获取家庭预算列表失败"}

async def remove_family_member(user_id, target_user_id):
    """
    移出家庭成员
    :param user_id: 操作者ID
    :param target_user_id: 目标用户ID
    :return: 操作结果
    """
    try:
        result = await family_repositories.remove_family_member(user_id, target_user_id)
        if result:
            return {"code": 0, "message": "移出成功"}
        return {"code": 1, "message": "移出失败，请检查权限或目标用户状态"}
    except Exception as e:
        print(f"移出家庭成员失败: {str(e)}")
        return {"code": 1, "message": "移出家庭成员失败"}

async def set_family_admin(user_id, target_user_id, is_promote):
    """
    设置家庭管理员
    :param user_id: 操作者ID
    :param target_user_id: 目标用户ID
    :param is_promote: 是否是升级操作
    :return: 操作结果
    """
    try:
        result = await family_repositories.set_family_admin(user_id, target_user_id, is_promote)
        if result:
            return {"code": 0, "message": "设置成功"}
        return {"code": 1, "message": "设置失败，请检查权限"}
    except Exception as e:
        print(f"设置家庭管理员失败: {str(e)}")
        return {"code": 1, "message": "设置家庭管理员失败"}

async def validate_phone(user_id, phone):
    """
    验证手机号
    :param user_id: 操作者ID
    :param phone: 手机号
    :return: 验证结果
    """
    try:
        # 验证手机号格式
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return False, "请输入有效的11位手机号码"

        # 检查手机号是否已注册
        user = await family_repositories.get_user_by_phone(phone)
        if not user:
            return {"code": 1, "message": "该手机号未注册"}

        # 检查用户是否已在家庭中
        if user.get('family_type', 0) != 0:
            return {"code": 1, "message": "该用户已加入其他家庭"}

        # 返回用户信息
        return {
            "code": 0, 
            "data": {
                "username": user['username'],
                "phone": phone
            }
        }
    except Exception as e:
        print(f"验证手机号失败: {str(e)}")
        return {"code": 1, "message": "验证手机号失败"}

async def send_invite(user_id, phone):
    """
    发送家庭邀请
    :param user_id: 操作者ID
    :param phone: 手机号
    :return: 操作结果
    """
    try:
        # 验证手机号格式
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return False, "请输入有效的11位手机号码"

        # 获取操作者信息和权限
        operator = await family_repositories.get_operator_info(user_id)
        if not operator:
            return {"code": 1, "message": "获取用户信息失败"}

        # 检查权限（创建者和管理员可以邀请）
        if operator['family_permissions'] > 1:
            return {"code": 1, "message": "您没有权限邀请新成员"}

        # 发送邀请
        result = await family_repositories.send_family_invite(
            user_id,
            phone
        )
        
        if result:
            return {"code": 0, "message": "邀请发送成功"}
        return {"code": 1, "message": "邀请发送失败"}
    except Exception as e:
        print(f"发送邀请失败: {str(e)}")
        return {"code": 1, "message": "发送邀请失败"}

async def create_family(user_id: int, family_name: str):
    """
    创建家庭
    :param user_id: 用户ID
    :param family_name: 家庭名称
    :return: 操作结果
    """
    try:
        # 参数验证
        if not family_name:
            return {"code": 1, "message": "家庭名称不能为空"}
        
        family_name = family_name.strip()
        if not family_name:
            return {"code": 1, "message": "家庭名称不能为空"}
            
        if len(family_name) > 50:
            return {"code": 1, "message": "家庭名称不能超过50个字符"}

        # 创建家庭
        result = await family_repositories.create_family(user_id, family_name)
        if result:
            return {"code": 0, "message": "创建成功"}
        return {"code": 1, "message": "创建失败，您可能已经在其他家庭中"}
    except Exception as e:
        print(f"创建家庭失败: {str(e)}")
        return {"code": 1, "message": "创建家庭失败，请稍后重试"}

async def check_family(user_id: int):
    """
    查询用户家庭状态
    :param user_id: 用户ID
    :return: 用户家庭信息
    """
    try:
        result = await family_repositories.check_family(user_id)
        if not result:
            return {"code": 1, "message": "获取用户信息失败"}
            
        return {
            "code": 0,
            "data": {
                "user_id": user_id,
                "family_type": result['family_type'],
                "family_permissions": result['family_permissions'],
                "family_name": result['family_name'],
                "invite_code": result['invite_code']
            }
        }
    except Exception as e:
        print(f"查询用户家庭状态失败: {str(e)}")
        return {"code": 1, "message": "查询用户家庭状态失败"}

async def delete_family(user_id: int) -> dict:
    """
    删除家庭
    :param user_id: 用户ID
    :return: 操作结果
    """
    try:
        result = await family_repositories.delete_family(user_id)
        if result:
            return {"code": 0, "message": "删除成功"}
        return {"code": 1, "message": "删除失败，只有创建者可以删除家庭"}
    except Exception as e:
        print(f"删除家庭失败: {str(e)}")
        return {"code": 1, "message": "删除家庭失败"}


# 加入家庭
async def join_family(user_id, invite_code) -> dict:
    """
    加入家庭
    :param user_id: 用户ID
    :return: 操作结果
    """
    try:
        result = await family_repositories.join_family(user_id, invite_code)
        if result:
            return {"code": 0, "message": "发送请求成功"}
        return {"code": 1, "message": "发送请求成功失败，验证码错误"}
    except Exception as e:
        print(f"加入家庭失败: {str(e)}")
        return {"code": 1, "message": "加入家庭失败"}